package com.flyxiaozhu.erp.core.utils;

import com.flyxiaozhu.erp.core.entities.IdSequence;
import com.flyxiaozhu.erp.core.repositories.IdSequenceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;

@Service
public class SnUtils {
    @Autowired
    IdSequenceRepository idSequenceRepository;

    private final long MAX_ID = 99900;

    /**
     * 生成订单号
     *
     * @param code 业务代码
     * @return 订单号
     */
    public String buildSn(BusinessCode code) {
        return buildSn(code, 12);
    }

    public String buildSn(BusinessCode code, int length) {
        Calendar calendar = Calendar.getInstance();
        String orderSn = String.format("%d%02d%02d%02d",
                code.value,                         //长度1
                calendar.get(Calendar.YEAR),        //长度4
                calendar.get(Calendar.MONTH),       //长度2
                calendar.get(Calendar.DAY_OF_MONTH) //长度2
        );
        int sLen = length - orderSn.length();
        orderSn += String.format("%0" + sLen + "d", getLatestId());

        return orderSn;
    }

    private long getLatestId() {
        IdSequence idSequence = new IdSequence();
        idSequenceRepository.save(idSequence);
        if (idSequence.getId() >= MAX_ID) {
            idSequenceRepository.resetId();
        }

        //每涨到1000个就清空
        if (idSequence.getId() % 1000 == 0) {
            idSequenceRepository.deleteAll();
        }

        return idSequence.getId();
    }

    public enum BusinessCode {
        SHOPPING_ORDER(1);

        int value;

        BusinessCode(int index) {
            this.value = index;
        }
    }
}
